// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-23

package choose_seat_info

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/logics/master/ticket/record"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 设置开始与结束时间.
type Logic struct {
	record.Logic

	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	ticket        *models.Ticket
	ticketRecord  *models.TicketRecord
	ticketSession *models.TicketSession

	request  *Request
	response []*Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)

	// 1. 事务处理.
	if err = db.Transaction(ctx,
		o.RunCheck,
		o.RunSeatList,
		o.RunSeatChosen,
	); err != nil {
		return res.WithError(err)
	}

	// 2. 绑定结果.
	return res.WithList(o.response)
}

// RunCheck
// 查询数据.
func (o *Logic) RunCheck(ctx context.Context, sess *db.Session) (err error) {
	var has bool

	// 1. 购买记录.
	if o.ticketRecord, has, err = services.NewTicketRecordService(sess).Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 无效记录.
	if !has || o.ticketRecord.ArcadeId != o.arcade.Id {
		err = errs.ErrTicketRecordNotFound
		return
	}

	// 3. 渔票数据.
	if o.ticket, has, err = services.NewTicketService(sess).Dao.GetById(ctx, o.ticketRecord.TicketId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has || o.ticket.ArcadeId != o.arcade.Id || o.ticket.Deleted.IsYes() {
		err = errs.ErrTicketNotFound
		return
	}

	// 4. 场次数据.
	if o.ticketSession, has, err = services.NewTicketSessionService(sess).Dao.GetById(ctx, o.ticketRecord.SessionId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	} else if !has || o.ticketSession.ArcadeId != o.arcade.Id || o.ticketSession.Deleted.IsYes() {
		err = errs.ErrTicketSessionNotFound
		return
	}

	// 6. 校验完成.
	return
}

// RunSeatChosen
// 读取已选钓位的钓友.
func (o *Logic) RunSeatChosen(ctx context.Context, sess *db.Session) (err error) {
	var (
		chosen = make(map[int64]kind.UserId)
		ids    = make([]kind.UserId, 0)
		list   []*models.TicketRecord
		users  map[kind.UserId]*models.Users
	)

	// 1. 购票记录.
	//    读取指定场次下的购票记录.
	if list, err = services.NewTicketRecordService(sess).Dao.ListByMap(ctx, map[string]any{
		"session_id": o.ticketRecord.SessionId,
	}); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 遍历记录.
	for _, item := range list {
		if item.SeatId > 0 {
			chosen[item.SeatId] = item.UserId
			ids = append(ids, item.UserId)
		}
	}

	// 3. 读取钓友.
	if len(ids) > 0 {
		if users, err = services.NewUsersService(sess).MapByIdList(ctx, ids); err != nil {
			err = errs.ErrDatabaseQuery
			return
		}
	}

	// 4. 绑定钓位.
	for _, r := range o.response {
		if uid, ok := chosen[r.Id]; ok {
			if u, has := users[uid]; has {
				r.WithUser(u)
			}
		}
	}
	return
}

// RunSeatList
// 读取钓位列表.
func (o *Logic) RunSeatList(ctx context.Context, sess *db.Session) (err error) {
	var list []*models.ArcadePondSeat

	if err = sess.Where("arcade_id = ? AND pond_id = ? AND deleted = ?",
		o.arcade.Id,
		o.ticket.PondId,
		kind.DeletedNo,
	).OrderBy("sort ASC").Find(&list); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	for _, item := range list {
		o.response = append(o.response, (&Response{}).With(item))
	}
	return
}
